package com.huazi.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huazi.eduservice.entity.EduSubject;
import com.huazi.eduservice.service.EduSubjectService;
import com.huazi.eduservice.vo.SubjectData;
import com.huazi.servicebase.exceptionhandler.MyException;

/**
 * @author shkstart
 * @create 2021-03-17 17:41
 */

public class SubjectDataListener extends AnalysisEventListener<SubjectData> {

    //因为subjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    //所以需要通过构造器传入mapper来实现(从controller传入service)
    public EduSubjectService subjectService;

    public SubjectDataListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    public SubjectDataListener() { }
    //读取数据（一行一行读取）
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        System.out.println("sub-"+subjectData);
        if(subjectData==null){
            //如果没有数据了就返回一个异常
            throw new MyException("文件没有数据！");
        }
        //一行一行读取数据
        //一级分类添加
        EduSubject eduOneSubject= this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if(eduOneSubject==null){
            eduOneSubject=new EduSubject();//如果不存在则创建该分类
            //设置title和“0”
            eduOneSubject.setParentId("0").setTitle(subjectData.getOneSubjectName());
            subjectService.save(eduOneSubject);//添加到数据库
        }
        //获取父id
        String pid = eduOneSubject.getSubId();//如果存在则有id，不存在则是
        //二级分类添加
        EduSubject eduTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(),pid);
        if(eduTwoSubject==null){
            eduTwoSubject=new EduSubject();//如果不存在则创建该分类
            //设置title和parent_id
            eduTwoSubject.setParentId( pid).setTitle(subjectData.getTwoSubjectName());
            subjectService.save(eduTwoSubject);//添加到数据库
        }
    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject=subjectService.getOne(wrapper);
        return oneSubject;
    }
    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService, String name, String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject oneSubject=subjectService.getOne(wrapper);
        return oneSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("sub-"+analysisContext);
    }

}
